import React, { useEffect, useState } from 'react'
import MyHeader from './components/MyHeader'
import MyFooter from './components/MyFooter'
import GoodsItem from './components/GoodsItem'
import './App.scss'
import axios from 'axios'
export default function App() {
  const [list, setList] = useState([])

  const changeStatus = (id) => {
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            goods_state: !item.goods_state,
          }
        } else {
          return item
        }
      })
    )
  }
  const changeAllSingle = (goods_state) => {
    // !#3 父组件根据接收到的参数来修改数据
    setList(
      list.map((item) => ({
        ...item,
        goods_state,
      }))
    )
  }

  useEffect(() => {
    const list = JSON.parse(localStorage.getItem('LIST')) || []
    // 本地有，就有本地的
    if (list.length) {
      return setList(list)
    }
    // 本地没有就发请求
    const getList = async () => {
      const {
        data: { list },
      } = await axios.get('https://www.escook.cn/api/cart')
      setList(list)
    }
    getList()
  }, [])

  useEffect(() => {
    localStorage.setItem('LIST', JSON.stringify(list))
  }, [list])

  // !#1 爷爷准备修改数据的方法并一层层传递给孙子
  const changeCount = (id, goods_count) => {
    // 爷爷根据接收到的数据进行修改
    setList(
      list.map((item) => {
        if (item.id === id) {
          return {
            ...item,
            goods_count,
          }
        } else {
          return item
        }
      })
    )
  }
  return (
    <div className='app'>
      <MyHeader>购物车</MyHeader>
      {list.map((item, index) => (
        <GoodsItem
          key={item.id}
          {...item}
          changeStatus={() => changeStatus(item.id)}
          index={index}
          changeCount={changeCount}
        />
      ))}
      <MyFooter list={list} changeAllSingle={changeAllSingle} />
    </div>
  )
}
